import type {
  ComputeContext,
  CreateCrudOptionsProps,
  CreateCrudOptionsRet,
  ScopeContext,
} from '@fast-crud/fast-crud';

import { ref, unref } from 'vue';

import { compute, dict } from '@fast-crud/fast-crud';

import { BaseEmployeeApi } from '#/api';
import { BaseRoleApi } from '#/api/basic/system/baseRole';
import { BaseOrgApi } from '#/api/basic/user/baseOrg';
import { useMessage } from '#/hooks/web/useMessage';
import { $t } from '#/locales';
import {
  createdTimeColumn,
  indexColumn,
  transformQuery,
} from '#/plugins/fast-crud/common';

export function createCrudOptions(
  props: CreateCrudOptionsProps,
): CreateCrudOptionsRet {
  const selectedRowKeys = ref<string[]>([]);
  const { createMessage } = useMessage();

  async function bindRole(flag: boolean, employeeIdList: string[]) {
    const formData = props.context;

    formData.bindEmployeeIds = await BaseRoleApi.saveRoleEmployee({
      flag,
      employeeIdList,
      roleId: formData.roleId,
    });

    createMessage.success('操作成功');
    props.crudExpose?.doRefresh();
  }

  return {
    selectedRowKeys,
    crudOptions: {
      request: {
        pageRequest: BaseEmployeeApi.pageRequest,
        transformQuery: (query) => {
          const tq = transformQuery(query);

          tq.model.roleId = props.context.roleId;
          return tq;
        },
      },
      actionbar: {
        buttons: {
          add: { show: false },
          bind: {
            type: 'primary',
            text: '批量绑定',
            click() {
              if (
                !unref(selectedRowKeys) ||
                unref(selectedRowKeys).length <= 0
              ) {
                createMessage.warning($t('common.tips.pleaseSelectTheData'));
                return;
              }
              bindRole(true, unref(selectedRowKeys));
            },
          },
          cancel: {
            danger: true,
            text: '批量取消',
            click() {
              if (
                !unref(selectedRowKeys) ||
                unref(selectedRowKeys).length <= 0
              ) {
                createMessage.warning($t('common.tips.pleaseSelectTheData'));
                return;
              }
              bindRole(false, unref(selectedRowKeys));
            },
          },
        },
      },
      table: {
        striped: true,
        rowKey: 'id',
        rowSelection: {
          type: 'checkbox',
          selectedRowKeys,
          onChange: (changed: string[]) => {
            selectedRowKeys.value = changed;
          },
        },
      },
      rowHandle: {
        width: 110,
        align: 'center',
        buttons: {
          edit: { show: false },
          copy: { show: false },
          view: { show: false },
          remove: { show: false },
          bind: {
            type: 'primary',
            danger: compute((context: ComputeContext) => {
              return !!props.context.bindEmployeeIds.includes(context.row.id);
            }),
            text: compute((context: ComputeContext) => {
              return props.context.bindEmployeeIds.includes(context.row.id)
                ? '解除绑定'
                : '绑定';
            }),
            click(context) {
              const flag = !props.context.bindEmployeeIds.includes(
                context.row.id,
              );
              bindRole(flag, [context.row.id]);
            },
          },
        },
      },
      columns: {
        ...indexColumn(props.crudExpose),
        username: {
          title: $t('devOperation.tenant.defUser.username'),
          type: 'text',
          column: {
            show: true,
            formatter: (context: ScopeContext) => {
              return context.form.defUser?.username;
            },
          },
        },
        mobile: {
          title: $t('devOperation.tenant.defUser.mobile'),
          type: 'text',
          search: { show: true },
          column: {
            show: true,
            formatter: (context: ScopeContext) => {
              return context.form.defUser?.mobile;
            },
          },
        },
        realName: {
          title: $t('basic.user.baseEmployee.realName'),
          type: 'text',
          search: { show: true },
        },
        orgIdList: {
          title: '所在部门',
          type: 'dict-tree',
          column: { show: false },
          search: { show: true, component: { multiple: true } },
          dict: dict({
            isTree: true,
            value: 'id',
            label: 'name',
            async getData() {
              return await BaseOrgApi.tree({});
            },
          }),
        },
        scope: {
          title: '范围',
          type: 'dict-radio',
          dict: dict({
            data: [
              { value: '-1', label: '全部', color: 'success' },
              { value: '1', label: '已绑定', color: 'error' },
              { value: '2', label: '未绑定', color: 'info' },
            ],
          }),
          column: { show: false },
          search: {
            show: true,
            component: {
              defaultValue: '-1',
            },
          },
        },
        ...createdTimeColumn({}),
      },
    },
  };
}
